var newFormTaskCtr = {};
(function(ctx,$){
    /**
     * 全局变量
     */
    var $domContainer = $("#field_container");
    var globalFormId,globalTransParams,globalFormFields,globalTaskFields,currentField,oldCustomData,globalvalidArray,ocrFields,isDhFields;

    /**
     * 入口函数
     */
    ctx.init = function(params){
        //初始化参数
        initParams(params);
        //初始化数据
        initData();
        //事件绑定
        initEvents();
    };



    /**
     * 参数初始化
     */
    var initParams = function(params){
        globalFormFields = [];
        globalTaskFields = [];
        ocrFields = [];
        globalTransParams = params ||{};
        globalFormId = params.formBaseInfo.formBaseInfo.formInfo.id;
        currentField = params.currentfield.name;
        oldCustomData = params.params;
    };

    /**
     * 获取表单和任务映射列表选项
     */
    var getPageOptions = function(callback){

        globalFormFields = [];
        globalTaskFields = [];
        getOcrFields();
        getIsDhFields();

        //主表标记
        // var isMasterTable = globalTransParams.currentfield.frontTableName == "front_formmain" ? true :false;
        var isMasterTable = false;
        //获取主表名称
        var tableName = globalTransParams.currentfield.tableName
        //主表表单字段
        var masterFormFields = globalTransParams.formBaseInfo.formBaseInfo.tableInfo.front_formmain.fieldInfo ||[];
        $.each(masterFormFields,function (i,v) {
            if(!v.isCustomCtrl){
                if(v.type === 'text'){
                    globalFormFields.push({key:v.name+"-"+tableName+"-"+0,name:'['+ $.i18n("form.ctrl.newformtask.maintable") +']' + v.display+"-"+tableName+"-"+0,fieldType:v.type});
                }
            }
        });

        //明细表表单字段
        var formsons = globalTransParams.formBaseInfo.formBaseInfo.tableInfo.formsons ||[];
        if(!isMasterTable){
            $.each(formsons,function (i,v) {
                var subTableName = v.tableName
                var detailFormFields =  v.fieldInfo ||[];
                $.each(detailFormFields,function (i,v) {
                    if(!v.isCustomCtrl){
                        var formsonType = v.formsonType.indexOf("二级明细区") > -1 ? 2 :1;
                        if(v.type === 'text'){
                            globalFormFields.push({key:v.name+"-"+subTableName+"-"+formsonType,name:'['+ $.i18n("form.ctrl.newformtask.detailtable") +']' + v.display+"-"+subTableName+"-"+formsonType,fieldType:v.type});
                        }
                    }
                });
            });
        }
        //执行回调
        if(callback && typeof callback === 'function'){
            callback.apply();
        }
    };


    /**
     * 获取ocr识别接口字段
     */
    var getOcrFields = function (){
        // ocrFields = [{"name":"张三","key":"Zhnagsn","fieldType":"text"},{"name":"李四","key":"lisi","fieldType":"text"}];
        //获取识别字段信息
        $.ajax({
            url: '/seeyon/rest/jssdk/getBaiDuOcrField',
            type: "GET",
            processData: false,
            contentType: false,
            async:false,
            success: function (data) {
                ocrFields = data
            },
            error: function (e) {
                console.log("获取百度Ocr识别票据异常，请检查配置文件！！！！！！！")
                ocrFields = [];
            }
        });
    }

    /***
     * 获取是否支持多行值
     */
    var getIsDhFields = function (){
        isDhFields = [{"name":"是","key":"1","fieldType":"text"},{"name":"否","key":"0","fieldType":"text"}];
    }


    /**
     * 数据加载
     */
    var initData = function(){
        //表单名称
        var formName = globalTransParams.formBaseInfo.formBaseInfo.formInfo.formName ||'';
        $("#formNameSpan").html("百度OCR识别字段映射");
        $("#formNameSpan").attr("title",formName);

        //下拉列表初始化
        getPageOptions(function(){
            $domContainer.empty();
            //初次设置则保持布局不动
            var rownum =  ocrFields.length ;
            if(oldCustomData && oldCustomData.fieldsMap && oldCustomData.fieldsMap.length > 0){
                rownum = oldCustomData.fieldsMap.length;
            }
            for(var i = 0 ; i< rownum ;i++){
                renderNewLineOfOptions(globalFormFields,globalTaskFields,ocrFields);
            }
            //回写多明细表关联字段配置信息
            if(oldCustomData){
                var glFieldValue = oldCustomData.glFieldValue
                var hxFjFieldValue = oldCustomData.hxFjFieldValue
                if(glFieldValue !== undefined){
                    $("#glFieldValue").val(glFieldValue);
                }
                if(hxFjFieldValue !== undefined){
                    $("#hxFjFieldValue").val(hxFjFieldValue);
                }
            }


            //回写ocrFields字段
            if(ocrFields){
                //已存在映射数据则回填
                if(oldCustomData){
                    $.each(oldCustomData.fieldsMap,function(index,v){
                        $domContainer.find("select.leftField").eq(index).val(v.ocrFiled);
                        $domContainer.find("select.rightField").eq(index).val(v.formField);
                        $domContainer.find("select.isDh").eq(index).val(v.isDh);
                    });
                }else{
                    $.each(ocrFields,function(index,v){
                        $domContainer.find("select.leftField").eq(index).val(v.key);
                    });
                }
            }
            //已存在映射数据则回填
            // if(oldCustomData){
            //     $.each(oldCustomData.fieldsMap,function(index,v){
            //         $domContainer.find("select.leftField").eq(index).val(v.ocrFiled);
            //         $domContainer.find("select.rightField").eq(index).val(v.formField);
            //     });
            // }
        });
    };

    /**
     * 初始化select下拉列表
     */
    var renderNewLineOfOptions = function(formFields,taskFields,ocrFields){

        var $newLine = $($("#field-maping-tpl").html());
        var $newLine_left = $newLine.find("select.leftField");
        var $newLine_right = $newLine.find("select.rightField");
        var $isDh = $newLine.find("select.isDh");

        var leftOptions ="";
        $.each(ocrFields,function (i,v) {
            leftOptions += '<option value="' + v.key + '" fieldType="'+ v.fieldType + '">' + v.name + '</option>';
            $domContainer.append($newLine);
        });
        $newLine_left.append(leftOptions);

        var rightOptions ="";
        $.each(formFields,function (i,v) {
            rightOptions += '<option value="' + v.key + '" fieldType="'+ v.fieldType +'">' + v.name + '</option>';
            $domContainer.append($newLine);
        });
        $newLine_right.append(rightOptions);

        var isDh ="";
        $.each(isDhFields,function (i,v) {
            isDh += '<option value="' + v.key + '" fieldType="'+ v.fieldType +'">' + v.name + '</option>';
            $domContainer.append($newLine);
        });
        $isDh.append(isDh);
    }

    /**
     * 事件绑定
     */
    var initEvents = function(){

        //增加行
        $domContainer.on('click','.cap-icon-zengjia',function(){
            renderNewLineOfOptions(globalFormFields,globalTaskFields,ocrFields);
        });

        //删除行
        $domContainer.on('click','.cap-icon-jianshao',function(){
            if($domContainer.find(".task-props-row").length > 1){
                $(this).parent().remove();
            }else{
                ctpTop.$.alert($.i18n("form.ctrl.newformtask.tips.delete")); //最后一条数据不可删除
            }
        });

        //自动过滤
        $domContainer.on('change','.leftField',function(){
            var rightOptions ="<option></option>";
            var $leftSelect = $(this).closest('.biz_groupguanlian').find(".leftField option:selected");
            var $rightSelect = $(this).closest('.biz_groupguanlian').find(".rightField");
            $rightSelect.empty();
            globalFormFields.forEach(function (opt) {
                var ff1 = $leftSelect.attr("fieldType") || "";
                var ff2 = opt.fieldType || "";
                if( ff2.indexOf(ff1) >=0 ){
                    rightOptions += '<option value="' + opt.key + '" fieldType="'+ opt.fieldType +'">' + opt.name + '</option>';
                }
            });
            $rightSelect.append(rightOptions);
        });
    }





    /**
     * 字段映射校验
     */
    var validate = function(leftField,rightField){
        var totalNum = $domContainer.find(".task-props-row").length;
        //未选中校验
        // if(((leftField.val() == "" && rightField.val() != "")
        //     || (rightField.val() == "" && leftField.val() != "")
        //     || (rightField.val() == "" && leftField.val() == "")) && totalNum >1){
        //     ctpTop.$.alert($.i18n("form.ctrl.newformtask.tips.empty")); //映射字段不允许为空，请重新选择。
        //     return false;
        // }
        // var ff1 = rightField.attr("fieldType") || "";
        // var ff2 = leftField.attr("fieldType") || "";
        // if( ff1.indexOf(ff2) < 0){
        //     //字段类型不匹配，请重新选择。
        //     ctpTop.$.alert( leftField.text() + $.i18n("form.ctrl.newformtask.tips.and") + rightField.text() + $.i18n("form.ctrl.newformtask.tips.notmap"));
        //     return false;
        // }else{
        //     var index = $.inArray(rightField.val(),globalvalidArray);
        //     if(index >= 0){
        //         //映射存在重复请重新选择。
        //         ctpTop.$.alert('['+ rightField.text()+']' +  $.i18n("form.ctrl.newformtask.tips.repeat"));
        //         return false;
        //     }else{
        //         globalvalidArray.push(rightField.val());
        //     }
        // }
        // var index = $.inArray(rightField.val(),globalvalidArray);
        // if(index >= 0){
        //     //映射存在重复请重新选择。
        //     ctpTop.$.alert('['+ rightField.text()+']' +  $.i18n("form.ctrl.newformtask.tips.repeat"));
        //     return false;
        // }else{
        //     globalvalidArray.push(rightField.val());
        // }
        globalvalidArray.push(rightField.val());
        return true;
    }

    /**
     * 确认按钮事件
     */
    ctx.submit = function(){
        globalvalidArray=[];

        var resultData = {},fieldsMap = [];
        //获取回写附件字段配置信息
        var hxFjFieldValue = $("#hxFjFieldValue").val();
        //获取多明细表之间关联字段
        var glFieldValue = $("#glFieldValue").val();
        var $items = $domContainer.find(".task-props-row");
        for(var i = 0; i < $items.length;i++){
            var $item = $($items[i]);
            var leftField  = $item.find(".leftField option:selected");
            var rightField = $item.find(".rightField option:selected");
            //逐一进行类型校验
            if(!validate(leftField,rightField)){
                return {valid :false};
            }else{
                fieldsMap.push({
                    ocrFiled : $item.find(".leftField").val(),
                    formField : $item.find(".rightField").val(),
                    isDh : $item.find(".isDh").val()
                });
            }
        }
        $.extend(resultData,{formId:globalFormId,fieldsMap:fieldsMap,glFieldValue:glFieldValue,hxFjFieldValue:hxFjFieldValue});
        return {valid: true,data:resultData};
    }
})(newFormTaskCtr,typeof $ === 'undefined' ? ctpTop.$ : $);